
import 'package:flutter/material.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/control/JmessageCtl.dart';
import 'package:juju/pages/ContactsPage.dart';
import 'package:juju/pages/MessagePage.dart';
import 'package:juju/pages/MyInfoPage.dart';

class NaviPages extends StatefulWidget {
  const NaviPages({Key? key}) : super(key: key);

  @override
  State<NaviPages> createState() => _NaviPagesState();
}

class _NaviPagesState extends State<NaviPages> {
  PageController? _pageController;
  int _index = 0;

  List<Widget> appPages = [
    const MessagePage(),
    const ContactsPage(),
    const MyInfoPage(),
  ];

  List<BottomNavigationBarItem> bottomNavigationBarItems = [
    const BottomNavigationBarItem(
      label: "聚聚",
      icon: Icon(Icons.chat_bubble_outline),
    ),
    const BottomNavigationBarItem(
      label: "通讯录",
      icon: Icon(Icons.contact_phone),
    ),
    const BottomNavigationBarItem(
      label: "我",
      icon: Icon(Icons.person),
    ),
  ];

  @override
  void initState() {
    super.initState();
    _checkLogin();
    _pageController = PageController(
      initialPage: 0,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: _pageController,
        scrollDirection: Axis.horizontal,
        onPageChanged: _pageChanged,
        children: appPages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: Colors.green,
        backgroundColor: Colors.grey[200],
        selectedIconTheme: const IconThemeData(size: 29.0),
        currentIndex: _index,
        items: bottomNavigationBarItems,
        onTap: _naviPageTo,
      ),
    );
  }

  void _naviPageTo(int index) {
    setState(() {
      _index = index;
    });
    if (_pageController!.hasClients) {
      _pageController!.animateToPage(
        index,
        duration: const Duration(milliseconds: 1),
        curve: Curves.easeInOut,
      );
    }
  }

  void _pageChanged(int index) {
    setState(() {
      _index = index;
    });
  }

  void _checkLogin() async {
    await getCurrentUserInfoCtl(IMConf.getInstance().getJmessage());
    setState(() {});
  }
}
